// pages/orderDetails/orderDetails.js
const orderService = require('../../../../api/orderService.js')
const wxbarcode = require('../../../../utils/self.js');
const util = require('../../../../utils/utils.js')
const teamBuyService = require('../../../../api/teamBuyService.js')
const advanceSellService = require('../../../../api/advanceSellService.js')
const storeService = require('../../../../api/storeService.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    memberName: '',
    mobile: '',
    goodsList: [],
    address: '',
    storeName: '',
    storeId: '',
    createTime: '',
    cashTotal: 0,
    remark: '',
    orderStatus: '',
    shipmentType: '',
    codeText: '',
    selfTimeScope: '立即到店',
    shipmentAmount: '0',
    isTeamBuy: false,
    isTeamShare: false,
    countDownList: {},
    teamMemberCount: '',
    joinMemberCount: '',
    joinMbrs: [],
    leaderImageUrl: '',
    teamMemberImageUrl: '',
    couponPrice: '0', //优惠券金额
    cardPrice: '0', //储值卡金额
    scoreAmount: '0', //抵扣积分
    serviceTel: '',
    canRefund: true,
    isDistribution: false,
    trackingCompany: '',
    trackingNumber: '',
    teamBuyEnd: false,
    teamStatus: 'normal', //success 成团  fail 失败 ongoing  进行中 normal 正常的
    orderType: 'normal', //normal  advanceSell 预售
    balanceEnable: true,
    balanceTotal: 0.00,
    business: 'RETAIL',
    deductibleShipmentAmonut: 0,
    payTime: 10,
    payTimeId: 0,
    groupTimeId: 0,
    hasRefund: false,
    order: {},
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
    storeInfo: {}
  },
  codeTextPartition: function (val) {
    console.log(val)
    val = val.replace(/\s/g, '').replace(/(\w{4})(?=\w)/g, "$1 ");
    console.log(val)
    return val;
  },
  handleOrderStatus: function (status) {
    if (status === "CREATED") {
      return "待付款"
    } else if (status === "PAID") {
      return "已付款"
    } else if (status === "SHIPPED") {
      return "配送中"
    } else if (status === "RECEIVED") {
      return "待评价"
    } else if (status === "FINISHED") {
      return "已完成"
    } else if (status === "CANCELED") {
      return "已取消"
    } else if (status === "REJECTED") {
      return "已退款"
    } else if (status === "RETURNING") {
      return "退款中 "
    } else if (status === "PENDING") {
      return "待自提"
    } else if (status === "WAITSHIPPED") {
      return "待发货"
    } else if (status === "WAITPAYBALANCE") {
      return "待付尾款"
    } else {
      return "状态异常"
    }
  },
  getOrderDetails: function () {
    let orderId = this.options.orderId
    var self = this
    orderService.getDetailsById(orderId).then(res => {
      console.log(res)
      if (res) {
        let itemStatus = res.status
        let tempData = {
          ...res,
          status: self.handleOrderStatus(res.status),
          cashTotal: (res.cashTotal).toFixed(2)
        }
        self.getOrderStoreInfo(res.storeId)
        this.setData({
          order: tempData,
          orderId: res.id,
          business: res.business,
          memberName: res.memberName,
          mobile: res.receiverMobile,
          goodsList: res.products,
          address: res.province + res.city + res.district + res.address,
          storeName: res.storeName,
          storeId: res.storeId,
          createTime: res.createTime,
          cashTotal: res.cashTotal,
          orderAmount: res.orderAmount,
          cashDeductTotal: res.cashDeductTotal,
          canRefund: res.canRefund,
          remark: res.remark,
          orderStatus: this.handleOrderStatus(itemStatus),
          deductibleShipmentAmonut: res.deductibleShipmentAmonut ? (res.deductibleShipmentAmonut).toFixed(2) : 0,
          storeAddress: res.storeAddress,
          selfTimeScope: res.selfTimeScope ? res.selfTimeScope : '',
          shipmentType: res.shipmentType,
          shipmentAmount: res.shipmentAmount,
          teamId: res.teamId ? res.teamId : '',
          teamLeaderRecordId: res.teamLeaderRecordId ? res.teamLeaderRecordId : '',
          advanceId: res.advanceId ? res.advanceId : '',
          hasRefund: res.hasRefund
        })
        // 付款倒计时
        if (res.status === 'CREATED') {
          self.getAutoCancelPeriod(res.createTime)
        }
        if (res.trackingCompany && res.trackingNumber) {
          self.setData({
            trackingCompany: res.trackingCompany,
            trackingNumber: res.trackingNumber
          })
        }
        if (res.shipmentType === "SELF" && res.ladingCode != '' && res.ladingCode != null) {
          this.setData({
            codeText: res.ladingCode
          })
          wxbarcode.barcode('barcode', this.data.codeText, 669, 122);
          setTimeout(() => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 669,
              height: 122,
              destWidth: 669,
              destHeight: 122,
              canvasId: 'barcode',
              success(res) {
                self.setData({
                  barcodeImageUrl: res.tempFilePath
                })
              }
            })
          }, 500);
          this.setData({
            codeText: this.codeTextPartition(this.data.codeText)
          })
        }
        // 拼团
        if (itemStatus === "PAID" && res.teamId != '' && res.teamId != null && res.canRefund) {
          if (self.data.teamLeaderRecordId) {
            self.setData({
              isTeamBuy: true,
              'order.status': "待拼团",
              isTeamShare: true,
            })
            self.getTeamBuyingInfo()
          }
        }
        // 团购
        if (res.teamId != '' && res.teamId != null) {
          let orderSelfScope = res.selfTimeScope
          let groupTime = []
          groupTime = orderSelfScope.split(" ")
          let daysArr = groupTime[0].split("-")
          let timeArr = groupTime[1].split("-")
          let startDate = daysArr[0].split(":")
          let endDate = daysArr[1].split(":")
          let day = startDate[1] + '月' + startDate[2] + '日-' + endDate[1] + '月' + endDate[2] + '日'
          let time = timeArr[0].slice(0, 5) + '-' + timeArr[1].slice(0, 5)
          let orderSelfTime = day + ' ' + time
          console.log(orderSelfTime)
          self.setData({
            selfTimeScope: orderSelfTime
          })
        }
        if (res.payments) {
          res.payments.forEach((i) => {
            if (i.payMethod === "COUPONPAY" && i.total !== res.deductibleShipmentAmonut) {
              self.setData({
                couponPrice: i.total
              })
            } else if (i.payMethod === "CARDPAY") {
              self.setData({
                cardPrice: i.total
              })
            } else if (i.payMethod === 'SCOREPAY') {
              self.setData({
                scoreAmount: i.total
              })
            }
          })
        }
        if (res.canRefund === false && itemStatus !== 'REJECTED') {
          self.setData({
            isTeamBuy: false,
            orderStatus: "退款中",
            isTeamShare: false,
          })
        }
        // 统配
        let distributionStore = []
        try {
          var storeData = wx.getStorageSync('wj_distributionStore')
          if (storeData) {
            distributionStore.push(storeData)
          }
          distributionStore.forEach((item) => {
            if (self.data.storeId === item.id) {
              self.setData({
                isDistribution: true
              })
            }
          })
        } catch (e) {}
        // 预售
        if (res.advanceId && itemStatus === 'WAITPAYBALANCE') {
          this.setData({
            balanceEnable: res.balanceEnable,
            balanceTotal: res.balanceTotal ? res.balanceTotal : '',
          })
        }
      }
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  getAutoCancelPeriod: function (createTime) {
    const self = this
    orderService.getAutoCancelPeriod().then(res => {
      let date = new Date()
      let createTimeStamp = new Date(createTime.replace(/-/g, '/')).getTime()
      let now = new Date(util.formatTime(date)).getTime()
      console.log(createTimeStamp, now)
      // 获取倒计时
      let timeArray = [];
      // 将活动的结束时间参数提成一个单独的数组，方便操作
      let tempTime = {
        openTeamTime: createTime,
        duration: res / 1000
      }
      timeArray.push(tempTime)
      console.log(timeArray)
      countDown()
      // 执行倒计时函数
      function countDown() {
        clearTimeout(self.data.payTimeId)
        let min = util.countDown(timeArray)[0].min
        let sec = util.countDown(timeArray)[0].sec
        if (min < 10) {
          min = min.substr(1)
          let payTime = min + ':' + sec
          self.setData({
            payTime: payTime
          })
        } else {
          let payTime = min + ':' + sec
          self.setData({
            payTime: payTime
          })
        }
        console.log(min)
        let time = setTimeout(
          function () {
            countDown(timeArray);
          }, 1000)
        self.setData({
          payTimeId: time
        })
      }
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  getTeamBuyingInfo: function () {
    var self = this
    var teamId = this.data.teamId
    var teamLeaderRecordId = this.data.teamLeaderRecordId
    teamBuyService.getDetails(teamId, teamLeaderRecordId).then(res => {
      console.log(res)
      this.setData({
        leaderImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        teamMemberImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        openTeamTime: res.openTeamTime, //开团时间
        duration: res.duration, //持续时间
        teamMemberCount: res.teamMemberCount,
        joinMbrs: res.joinMbrs,
        originalPrice: res.originalPrice,
        joinMemberCount: res.joinMemberCount ? res.joinMemberCount : 0,
      })
      let tempItem = []
      res.joinMbrs.forEach((i) => {
        tempItem.push({
          ...i,
          memberImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        });
      })
      self.setData({
        joinMbrs: tempItem
      })
      console.log(self.data.joinMbrs)
      /**
       * 先判断成团
       * 再判断时间
       * teamStatus:'normal', //success 成团  fail 失败 ongoing  进行中 normal 正常的
       */
      if (res.teamMemberCount === res.joinMemberCount) {
        // 已经成团
        self.setData({
          teamStatus: 'success'
        })
      } else {
        // 未成团
        var data = new Date()
        var nowDate = new Date().getTime();
        let openTiem = 0
        if (self.data.openTeamTime) {
          openTiem = new Date(self.data.openTeamTime.replace(/-/g, '/')).getTime()
        } else {
          openTiem = nowDate
          self.setData({
            openTeamTime: (util.formatTime(data)).replace(/\//g, '-')
          })
          console.log(self.data.openTeamTime)
        }
        let duration = (nowDate - openTiem) / 1000
        console.log(duration, self.data.openTeamTime, self.data.duration)
        if (duration >= self.data.duration) {
          self.setData({
            teamBuyEnd: true
          });
        }
        if (self.data.teamBuyEnd === false) {
          // 获取倒计时
          let teamBuyTimeInfo = [];
          // 将活动的结束时间参数提成一个单独的数组，方便操作
          let tempTime = {
            openTeamTime: this.data.openTeamTime,
            duration: this.data.duration
          }
          teamBuyTimeInfo.push(tempTime)
          this.setData({
            teamBuyTimeList: teamBuyTimeInfo
          });
          console.log(teamBuyTimeInfo)
          countDown()
          // 执行倒计时函数
          function countDown() {
            clearTimeout(self.data.groupTimeId)
            self.setData({
              countDownList: util.countDown(teamBuyTimeInfo)[0]
            })
            if (self.data.countDownList.hou == '00' && self.data.countDownList.min == '00' && self.data.countDownList.sec == '00') {
              self.setData({
                teamBuyEnd: true
              })
            }
            let time = setTimeout(
              function () {
                countDown(teamBuyTimeInfo);
              }, 1000)
            self.setData({
              groupTimeId: time
            })
          }
        } else {
          wx.showToast({
            title: '当前团购活动已过期...',
            icon: 'none',
            duration: 1000
          })
          // self.setData({
          //   orderStatus:'退款中',
          //   isTeamShare:false
          // })
        }
      }
    })
  },
  getByOrder: function (orderId) {
    console.log(orderId)
    orderService.getByOrder(orderId).then(res => {
      console.log(res)
    })
  },
  toGoodsDetails: function (val) {
    wx.navigateTo({
      url: '../../goods/goodsDetail/goodsDetail?productId=' + val.currentTarget.dataset.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  toCancel: function (val) {
    var self = this
    console.log(val)
    let orderId = val.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确认要取消该订单？',
      success: function (res) {
        if (res.confirm) {
          orderService.cancel(orderId).then(item => {
            self.getOrderDetails()
          })
        } else if (res.cancel) {}
      }
    })
  },
  toPay: function () {
    let orderId = this.data.orderId
    this.toPayMethod(orderId, 'normal')
  },
  // 前往支付页面
  toPayMethod: function (orderId, type) {
    wx.navigateTo({
      url: '../../pay/payMethod/payMethod?orderId=' + orderId + '&from=order&type=' + type
    })
  },
  // 支付成功
  toPaymentSuccess: function (orderId) {
    wx.navigateTo({
      url: '../../pay/payment/payment?orderId=' + orderId
    })
  },
  // 支付尾款
  toPayTail: function () {
    const that = this
    let tempData = {
      orderId: this.data.orderId,
      // payMethod: 'SWIFTPASS'
      payMethod: 'WX_MINI_APP'
    }
    const advanceId = that.data.advanceId
    const orderId = that.data.orderId
    const goodsList = that.data.goodsList
    let productId = null
    if (goodsList.length > 0) {
      productId = goodsList[0].productId
    }
    advanceSellService.getByIds(advanceId, productId).then(res => {
      console.log(res)
      let now = new Date()
      let nowTimeStamp = new Date(util.formatTime(now)).getTime()
      const startTimeStamp = new Date(res.balanceStartTime.replace(/-/g, '/')).getTime()
      const endTimeStamp = new Date(res.balanceEndTime.replace(/-/g, '/')).getTime()
      const startTime = res.balanceStartTime.split(" ")[0]
      const startArray = startTime.split("-")
      const newStart = startArray[0] + '年' + startArray[1] + '月' + startArray[2] + '日'
      const endTime = res.balanceEndTime.split(" ")[0]
      const endArray = startTime.split("-")
      const newEnd = endArray[0] + '年' + endArray[1] + '月' + endArray[2] + '日'
      if (nowTimeStamp < startTimeStamp) {
        // 未到支付尾款时间
        wx.showToast({
          title: '请于' + newStart + '至' + newEnd + '期间支付尾款',
          icon: 'none',
          duration: 2000
        })
      } else if (startTimeStamp <= nowTimeStamp && nowTimeStamp <= endTimeStamp) {
        // 支付尾款时间段内
        // getPaySign()
        self.toPayMethod(orderId, 'payTail')
      } else {
        // 已过支付尾款时间
        wx.showToast({
          title: '很抱歉，您的订单已经超过支付尾款的最后期限了~',
          icon: 'none',
          duration: 2000
        })
      }

    })

    function getPaySign() {
      advanceSellService.getBalancePaySign(tempData).then(res => {
        console.log(res)
        var resData = JSON.parse(res);
        var sign = JSON.parse(resData.sign)
        let packageValue = ''
        if (tempData.payMethod === 'SWIFTPASS') {
          packageValue = sign.package
        } else if (tempData.payMethod === 'WX_MINI_APP') {
          packageValue = sign.packageValue
        }
        wx.requestPayment({
          'timeStamp': sign.timeStamp,
          'nonceStr': sign.nonceStr,
          'package': packageValue,
          'signType': sign.signType,
          'paySign': sign.paySign,
          'success': function (res) {
            let orderId = tempData.orderId
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.getOrderDetails()
          },
          'fail': function (res) {
            console.log('支付失败')
            console.log(res)
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                title: '您取消了订单支付~',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  handleConfirmReceipt: function (val) {
    var self = this
    console.log(val)
    let orderId = val.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '请确认已经收到商品？',
      success: function (res) {
        if (res.confirm) {
          orderService.confirm(orderId).then(item => {
            self.getOrderDetails()
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 前往订单轨迹页面
  toOrderTrajectory: function () {
    const that = this
    let order = this.data.order
    let orderId = order.id
    let tempLocation = {
      store: {
        latitude: that.data.order.lat,
        longitude: that.data.order.lng,
      },
      user: {
        latitude: that.data.storeInfo.latitude,
        longitude: that.data.storeInfo.longitude,
      }
    }
    let location = JSON.stringify(tempLocation)
    wx.navigateTo({
      url: '../orderTrajectory/orderTrajectory?orderId=' + orderId + '&location=' + location
    })
  },
  toRefundGoods: function (val) {
    console.log(val)
    let orderId = val.currentTarget.dataset.id
    wx.navigateTo({
      url: '../refund/refund?orderId=' + orderId
    })
  },
  toRefundDetails: function (val) {
    let orderId = val.currentTarget.dataset.id
    wx.navigateTo({
      url: '../refundDetails/refundDetails?orderId=' + orderId
    })
  },
  toEvaluate: function (val) {
    let orderId = val.currentTarget.dataset.id
    wx.navigateTo({
      url: '../evaluate/evaluate?orderId=' + orderId
    })
  },
  toService: function () {
    const tel = this.data.serviceTel
    wx.showModal({
      title: '提示',
      content: '确认要拨打此电话' + tel + ' ？',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: tel,
          })
        } else if (res.cancel) {}
      }
    })
  },
  toTrackingDetails: function () {
    const that = this
    let tempData = {
      trackingCompany: that.data.trackingCompany,
      trackingNumber: that.data.trackingNumber
    }
    let trackData = JSON.stringify(tempData);
    wx.navigateTo({
      url: '../logisticsInfo/logisticsInfo?trackData=' + trackData
    })
  },

  /**
   * 联系门店
   */
  contactStore: function () {
    const that = this
    const storeId = this.data.order.storeId
    let storeInfo = {
      tel: ''
    }
    try {
      let allStores = wx.getStorageSync('wj_allStores')
      if (allStores && allStores.length > 0) {
        for (let i = 0; i < allStores.length; i++) {
          const item = allStores[i]
          if (item.id == storeId) {
            storeInfo = item;
            break;
          }
        }
      }
    } catch (e) {
      console.log("123")
    }
    if (storeInfo.tel !== '') {
      wx.showModal({
        title: '提示',
        content: '确定要拨打以下电话' + storeInfo.tel + '?',
        confirmText: '拨打',
        success: function (res) {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: storeInfo.tel,
            })
          }
          if (res.cancel) {

          }

        }
      })
    }
  },
  getOrderStoreInfo: function (storeId) {
    const self = this
    let storeInfo = {
      tel: ''
    }
    try {
      let allStores = wx.getStorageSync('wj_allStores')
      if (allStores && allStores.length > 0) {
        for (let i = 0; i < allStores.length; i++) {
          const item = allStores[i]
          if (item.id == storeId) {
            storeInfo = item;
            break;
          }
        }
        self.setData({
          storeInfo: storeInfo
        })
      } else {
        storeService.queryList().then(res => {
          var allStores = [];
          res.forEach(item => {
            if (item.status === 'OPEN') {
              allStores.push(item)
            }
            if (item.id == storeId) {
              storeInfo = item
            }
          });
          try {
            wx.setStorageSync('wj_allStores', allStores)
          } catch (e) {
            console.log(e)
          }
          self.setData({
            storeInfo: storeInfo
          })
        }).catch(err => {
          console.log(err.message)
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      }
    } catch (e) {
      console.log(e)
    }
  },
  /**
   * 查看门店位置
   */
  viewStoreLocation: function () {
    const that = this
    const storeId = this.data.order.storeId
    let storeInfo = {
      tel: ''
    }
    try {
      let allStores = wx.getStorageSync('wj_allStores')
      if (allStores && allStores.length > 0) {
        for (let i = 0; i < allStores.length; i++) {
          const item = allStores[i]
          if (item.id == storeId) {
            storeInfo = item;
            break;
          }
        }
      }
      console.log(storeInfo)
      const latitude = parseFloat(storeInfo.latitude)
      const longitude = parseFloat(storeInfo.longitude)
      wx.openLocation({
        latitude,
        longitude,
        scale: 28,
        name: storeInfo.name,
        address: storeInfo.address
      })
    } catch (e) {
      console.log(e)
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    this.setData({
      serviceTel: app.globalData.servicePhone
    })
    console.log(options.orderId)
    if (options.orderId) {
      this.getOrderDetails()
      //this.getByOrder(options.orderId)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.options.orderId) {
      this.getOrderDetails()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("123")
    clearTimeout(this.data.payTimeId)
    clearTimeout(this.data.groupTimeId)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const that = this
    let storeData = JSON.stringify({
      storeId: this.data.storeId,
      storeName: this.data.storeName
    });
    const goods = that.data.goodsList
    let imgUrl = null
    if (goods.length > 0) {
      imgUrl = goods[0].imageUrl
    }
    if (res.from === 'button') {
      // 来自页面内转发按钮
      if (app.globalData.userInfo && app.globalData.userInfo.member) {
        let memberId = app.globalData.userInfo.member.id
        return {
          title: '拼团有优惠',
          path: '/pages/mallModule/fightGroup/groupPurchase/groupPurchase?teamBuyId=' + this.data.teamId + '&teamLeaderRecordId=' + this.data.teamLeaderRecordId + '&storeData=' + storeData + '&mobile=' + memberId,
          imageUrl: imgUrl,
          success(e) {
            wx.showShareMenu({
              withShareTicket: true
            })
          }
        }
      } else {
        return {
          title: '无界门店商城让生活更便利',
          path: '/pages/mallModule/index/index/index',
          imageUrl: imgUrl,
          success(e) {
            wx.showShareMenu({
              withShareTicket: true
            })
          }
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/index/index/index',
        imageUrl: imgUrl,
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  /**
   * 打开弹窗
   */
  toggleMiddlePopup() {
    this.toggle('middle');
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type]
    });
  }
})